﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Polenter.Serialization;
using System.IO;

namespace ZKCache
{
    public class CacheIndex
    {
        const string cacheIndexFile = "cacheIndex.index";
        private List<CacheDictionary> cachePool;

        public CacheIndex()
        {
            cachePool = new List<CacheDictionary>();
        }
        public void LoadFromDisk(string path)
        {
            if (File.Exists(path + cacheIndexFile))
            {
                SharpSerializer serializer = new SharpSerializer(false);
                cachePool = serializer.Deserialize(path + cacheIndexFile) as List<CacheDictionary>;
            }
        }

        public void Synchronize(string path)
        {
            SharpSerializer serializer = new SharpSerializer(false);
            serializer.Serialize(cachePool, path + cacheIndexFile);
        }

        public CacheDictionary cacheDictionaryWithIdentifier(string identifier)
        {
            CacheDictionary cache = cachePool.Find(c =>
                {
                    return c.identifier.Equals(identifier);
                });
            return cache;
        }
        public void CreateCache(CacheDictionary cache, object willCacheObj,string path)
        {
            int index = cachePool.FindIndex(c =>
            {
                return c.identifier == cache.identifier;
            });
            if (index == -1)
                cachePool.Add(cache);
            else
                cachePool[index] = cache;

            SharpSerializer serializer = new SharpSerializer(false);
            serializer.Serialize(willCacheObj, path + cache.identifier + ".cache");
            Synchronize(path);
        }

        public void cleanPool()
        {
            cachePool.ForEach(p =>
                {
                    File.Delete(p.cachePath);
                });
            cachePool.Clear();
        }
    }
}
